<template>
  <el-page-header @back="goBack">
    <template #content>
      <span class="text-large font-600 mr-3">药品搜索</span>
    </template>
  </el-page-header>
  <div class="search-form-wrapper">

    <el-form class="search-form" ref="searchForm" :model="searchForm" inline>
      <el-form-item label="药品名称/症状:">
        <el-input v-model="searchForm.keyword" placeholder="请输入药品名称或症状" class="search-input"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchDrugs">搜索</el-button>
        <el-button type="danger"  @click="oncar">购物车</el-button>
      </el-form-item>
    </el-form>


  </div>

  <el-table :data="pagedDrugList" style="width: 100%" v-loading="loading">
    <el-table-column fixed prop="drugs" label="药品名称" width="150" />
    <el-table-column prop="picture" label="药品图片" width="120">
      <template #default="scope">
        <el-image :src="attachImg(scope.row.picture)" width="150px"/>
      </template>
    </el-table-column>
    <el-table-column prop="drugprice" label="药品价格" width="120" />
    <el-table-column prop="drugdescription" label="症状类型" width="120" />
    <el-table-column prop="brand" label="药物品牌" width="120" />
    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">
        <el-button type="primary" size="default" @click="showDetails(scope.row)">
          详情
        </el-button>
        <el-button type="danger" size="default" @click="addShopcar(scope.row)">
          购买
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
      background
      layout="prev, pager, next"
      :total="totalCount"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      @update:current-page="onPageChange"
      @update:page-size="onPageSizeChange"
      :hide-on-single-page="issingle"
      v-show="showPagination"
  />

  <el-drawer
      v-model="drawer"
      title="药品详情"
      size="30%"
      :with-header="false"
  >
    <div class="drug-details">
      <div class="drug-info" v-if="currentDrug">
        <h2>{{ currentDrug.drugs }}</h2>
        <p><strong>价格:</strong> {{ currentDrug.drugprice }}</p>
        <p><strong>规格:</strong> {{ currentDrug.consumption }}</p>
        <p><strong>适应症:</strong> {{ currentDrug.indication }}</p>
        <p><strong>用法用量:</strong> {{ currentDrug.metering }}</p>
        <p><strong>主要成分:</strong> {{ currentDrug.component }}</p>
        <p><strong>用药禁忌:</strong> {{ currentDrug.taboo }}</p>
        <p><strong>不良反应:</strong> {{ currentDrug.reaction }}</p>
        <p><strong>药物相互作用:</strong> {{ currentDrug.effect }}</p>
        <p><strong>注意事项:</strong> {{ currentDrug.matter }}</p>
        <p><strong>药理毒性:</strong> {{ currentDrug.toxicity }}</p>
        <p><strong>药物品牌:</strong> {{ currentDrug.brand }}</p>
        <p><strong>药品类型:</strong> {{ currentDrug.type }}</p>
        <p><strong>药品计量:</strong> {{ currentDrug.dose }}</p>
        <p><strong>药物性状:</strong> {{ currentDrug.character }}</p>
        <p><strong>药物存储:</strong> {{ currentDrug.storage }}</p>
        <p><strong>药品保质期:</strong> {{ currentDrug.period }}</p>
        <p><strong>批准文号:</strong> {{ currentDrug.approval }}</p>
        <p><strong>生产厂家:</strong> {{ currentDrug.manufactor }}</p>
      </div>
    </div>
  </el-drawer>

  <el-drawer
      class="shopping-cart-drawer"
      v-model="drawer1"
      title="加入购物车"
      :with-header="false"
      size="30%"
  >
    <div v-if="currentDrug" class="drawer-content">
      <h2 class="drug-name">{{ currentDrug.drugs }}</h2>
      <p class="drug-price"><strong>单价:</strong> {{ currentDrug.drugprice }}</p>
      <el-input-number v-model="num" :min="1" :max="10" @change="handleChange" class="drug-quantity-input" />
      <el-button type="danger" size="default" @click="addToCartConfirm" class="add-to-cart-button">加入购物车</el-button>
    </div>
  </el-drawer>
</template>


<script>
import axios from "axios";
import { ElMessage } from "element-plus";
import {attachImg} from "@/api";

export default {
  name: "SearchDrugs",
  data() {
    return {
      searchForm: {
        keyword: ""
      },
      drugList: [],
      loading: false,
      drawer:false,
      drawer1:false,
      currentDrug:null,
      num: 1, // 默认购买数量
      currentPage: 1,
      pageSize: 4,
      totalCount: 0,
      issingle: true,
      showPagination: true,
    };
  },
  computed: {
    pagedDrugList() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.drugList.slice(start, end);
    },
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.searchDrugs();
    });
  },
  methods: {
    addToCartConfirm() {

      // 假设你有一个后端API来处理添加到购物车的操作
      const cartItem = {
        status:1,
        userid: localStorage.getItem('userId'), // 从localStorage获取用户ID
        drugid: this.currentDrug.drugsid, // 当前药品的ID
        drugname: this.currentDrug.drugs, // 当前药品的名称
        drugnumber: this.num, // 用户选择的数量
        drugprice: this.currentDrug.drugprice, // 药品的价格
        pictrue: this.currentDrug.picture // 药品的图片路径
      };
      // 设置请求头，确保Content-Type为application/json
      const config = {
        headers: {
          'Content-Type': 'application/json'
        }
      };
      // 使用axios发送POST请求到后端API
      axios.post('http://localhost:9099/cart/add', cartItem,config)
          .then(response => {
            ElMessage({
              message:response.data.msg,
              type:'success',
              duration:2000
            })
            // 处理响应，例如显示成功消息
            console.log('Added to cart:', response.data);
          })
          .catch(error => {
            // 处理错误，例如显示错误消息
            console.error('Error adding to cart:', error);
          });

      // 关闭抽屉
      this.drawer1 = false;
    },
    showDetails(drug) {
      this.currentDrug = drug; // 设置当前点击的药品对象
      this.drawer = true; // 显示抽屉
    },
    addShopcar(drug) {
      this.currentDrug = drug; // 设置当前点击的药品对象
      this.drawer1 = true; // 显示抽屉
    },
    attachImg,
    searchDrugs() {
      const token = localStorage.getItem("sessionToken"); // 从localStorage获取token
      this.loading = true;
      axios
          .get(`http://localhost:9099/store/querybycondition`, {
            params: { keyword: this.searchForm.keyword },
            headers: { Authorization: token }, // 手动设置Authorization头部
          })
          .then(response => {
            this.drugList = response.data.data;
            this.totalCount = this.drugList.length;
            this.loading = false;
          })
          .catch(error => {
            this.loading = false;
            ElMessage.error("搜索失败: " + error.message);
          });
    },
    goBack() {
      // 后退逻辑
    },
    onPageChange(newPage) {
      this.currentPage = newPage;
    },
    onPageSizeChange(newSize) {
      this.pageSize = newSize;
    },
    oncar(){
      this.$router.push('/HomePage/shopcar')
    },
  }
};
</script>

<style scoped>
.search-form {
  margin-top: 20px;

}

.search-input {
  width: 240px;
}


.drug-details {
  padding: 20px;
  font-size: 14px;
  line-height: 1.5;
}

.drug-details h2 {
  margin-top: 0;
  color: #333;
}

.drug-info p {
  margin: 5px 0;
}

.drug-info p strong {
  color: #666;
}
/* 抽屉内容样式 */
.shopping-cart-drawer .drawer-content {
  padding: 20px;
}

.shopping-cart-drawer .drug-name {
  margin-bottom: 16px;
}

.shopping-cart-drawer .drug-price {
  margin-bottom: 16px;
}

.shopping-cart-drawer .drug-quantity-input {
  margin-bottom: 20px;
  width: 50%; /* 使输入框宽度适应抽屉宽度 */
}

.shopping-cart-drawer .add-to-cart-button {
  width: 60%; /* 使按钮宽度适应抽屉宽度 */
  margin-top: 10px;
}
.search-form {
  display: flex;
  justify-content: flex-start;
}
</style>